
#! coding=utf-8
import sys,subprocess
import os,time
import glob

week = {0:'周一', 1:'周二', 2:'周三', 3:'周四', 4:'周五', 5:'周六', 6:'周日'}

now = time.localtime() 
runid = sys.argv[1]
dir1 = f'/data/share/'
dir2 = f'/data/mNGS/runmngs/GZ/'
begFile = glob.glob(f'{dir2}/*.{runid}.csv')[0]
endFile = f'{dir1}/{runid}/L01/SequenceStat.txt'
kkFile = glob.glob(f'{dir2}/{runid}/GZ.mNGS.*.mergeKK.xlsx')[0]
ntFile = glob.glob(f'{dir2}/{runid}/GZ.mNGS.*.mergeNT.xlsx')[0]


beg_time = os.path.getmtime(begFile)
begtime = time.strftime('%H:%M', time.localtime(beg_time))
end_time = os.path.getmtime(endFile)
endtime = time.strftime('%H:%M', time.localtime(end_time))
fastqNum = int(subprocess.getoutput(f"ls {dir2}/{runid}/fastq/*.gz | wc -l ").split()[0])

kkflag = 0
ntflag = 0
while 1:
    if kkflag == 0 and os.path.exists(kkFile):
        kkflag = 1
        kk_time = os.path.getmtime(kkFile)
        kktime = time.strftime('%H:%M', time.localtime(kk_time))

    if ntflag == 0 and os.path.exists(ntFile):
        ntflag = 1
        nt_time = os.path.getmtime(ntFile)
        nttime = time.strftime('%H:%M', time.localtime(nt_time))
    if kkflag ==1 and ntflag ==1:
        break
    else:
        time.sleep(60)

if time.localtime(kk_time) > time.localtime(nt_time):
    downloadtime = kktime
else:
    downloadtime = nttime
with open(f'/data/pub/today/guangzhou/{runid}/{runid}.time.xls','w',encoding='gbk') as out:
    out.write(f'广州\t{runid}\t{fastqNum}\t\t{week[now.tm_wday]}\t{begtime}\t{endtime}\t{kktime}\t{nttime}\t{downloadtime}\n')

script = f''' cp -r /data/mNGS/runmngs/GZ/{runid}/*/*kk.ra.xls  /data/pub/today/guangzhou/{runid}/ra/ && cp -r /data/mNGS/runmngs/GZ/{runid}/*/*nt.ra.xls  /data/pub/today/guangzhou/{runid}/ra/  &&  cp -r /data/mNGS/runmngs/GZ/{runid}/*/*gene_mapping* /data/pub/today/guangzhou/{runid}/rgi/  && cp -r /data/mNGS/runmngs/GZ/{runid}/QC_report_{runid}.xlsx /data/pub/today/guangzhou/{runid}/  && cd /data/pub/today/guangzhou && tar zcvf {runid}.tar.gz {runid} '''
subprocess.run(script,shell=True)
